#include "server.h"
#include "../../../client/qt_messenger/network/netparam.h"
Server::Server(int listenPort, QObject *parent):QTcpServer(parent)
{
    if(!listen(QHostAddress::Any,listenPort))
        emit notify(QString(),NetError::SERVER_LISTEN_FAIL);// server can't listen on the port
    connect(this,SIGNAL(newConnection(Connection *)),SLOT(onNewConnection(Connection*)));
    connect(this,SIGNAL(recieveData(QString,QByteArray)),SLOT(onRecieveData(QString,QByteArray)));
}
void Server::onCloseConnection(QString ip)
{
    if(ip.isEmpty()) return;
    if(!conns.contains(ip))
    {
        qDebug("in server,try to close a non-existed connection ");
        return;
    }
    Connection *conn=conns.value(ip);
    conn->close();
    conns.remove(ip);// remove from conn list,will deletelater
    qDebug("in server,remove connection from ip:%s",ip.toAscii().data());
}

void Server::onSendData(QString ip, QByteArray data)
{
    if(ip.isEmpty() || data.isEmpty())
        return;
    if(!conns.contains(ip)) return;
    qDebug("in server,send data to %s",ip.toAscii().data());
    conns.value(ip)->onSendData(data);// just call,use slot as a normal method
}

void Server::onNewConnection(Connection *conn)
{
    if(conn==NULL)
        return;
    if(conns.contains(conn->ipTo))
    {
        qDebug("in server,remove old connection %s",conn->ipTo.toAscii().data());
        onCloseConnection(conn->ipTo);
    }
    qDebug("a new connection coming from %s",conn->ipTo.toAscii().data());
    addNewConnection(conn);
}

void Server::addNewConnection(Connection *conn)
{
    if(conn==NULL) return;
    conns.insert(conn->ipTo,conn);
    connect(conn,SIGNAL(notify(QString,int)),this,SIGNAL(notify(QString,int)));// connect connection to client
    connect(conn,SIGNAL(recieveData(QString,QByteArray)),SIGNAL(recieveData(QString,QByteArray)));
}


void Server::incomingConnection(int socketDescriptor)
{
    Connection *connection = new Connection(this);
    connection->setSocketDescriptor(socketDescriptor);
    connection->ipTo = connection->peerAddress().toString();
    emit newConnection(connection);
}

void Server::onRecieveData(QString ip, QByteArray data)
{
    qDebug("in server,recieve data from %s",ip.toAscii().data());
}
